package
{
	import com.xcopy.Screen;
	import flash.display.MovieClip;

	// 數位燈箱控制元件
	public class DigitalBox extends Screen
	{
		public var digits:Array      = []; // 數字
		public var commas:Array      = []; // 千分
		protected var _number:Number = 0; // 目前的數字
		protected var _target:Number = 0; // 目標的數字
		protected var _serial:Number = 0; // 目標的序號
		protected var _minus:Boolean = false; // 目標數字小於 0
		public var TIME_STEP:Number  = 1.6; // 數字變化時間

		public function DigitalBox(r:* = null)
		{
			super(r);
		}

		override public function set clip(c:MovieClip):void
		{
			super.clip = c;
			var i:Number = 0;
			var mc:MovieClip;
			for (i = 0; i < 10; i++)
			{
				mc = clip.getChildByName('oDigit' + (i + 1)) as MovieClip;
				if (mc != null)
				{
					digits[i] = mc; // 將數字燈放入陣列
				}
			}
			for (i = 0; i < 3; i++)
			{
				mc = clip.getChildByName('oComma' + (i + 1)) as MovieClip;
				if (mc != null)
				{
					commas[i] = mc; // 將千分燈放入陣列
				}
			}
			number = 0;
		}

		public function set number(n:Number):void
		{
			_number = Math.floor(n);
			_minus = (n < 0);
			var s:String = String(Math.abs(_number));
			var i:Number = 0;
			//trace('指定數字為：' + _number + '');
			for (i = 0; i < digits.length; i++)
			{
				if (i < s.length)
				{
					digits[i].visible = true;
					digits[i].gotoAndStop('Num' + s.substr(s.length - i - 1, 1));
				}
				else
				{
					digits[i].visible = false;
				}
				if (i % 3 == 0 && i > 0 && commas[Math.floor(i / 3) - 1] != null)
				{
					commas[Math.floor(i / 3) - 1].visible = (s.length > i);
				}
			}
		}

		public function get number():Number
		{
			return _number;
		}

		public function set target(n:Number):void
		{
			_target = n;
			addTween(this, {time: TIME_STEP, number: n, transition: 'linear'});
		}

		public function get target():Number
		{
			return _target;
		}

		public function set serial(n:Number):void
		{
			_serial = Math.floor(n);
			_minus = (n < 0);
			var s:String = String(Math.abs(_serial));
			var i:Number = 0;
			//trace('指定數字為：' + _number + '');
			for (i = 0; i < digits.length; i++)
			{
				if (i < s.length)
				{
					digits[i].visible = true;
					digits[i].gotoAndStop('Num' + s.substr(s.length - i - 1, 1));
				}
				else
				{
					digits[i].visible = true;
					digits[i].gotoAndStop('Num0');
				}
				if (i % 3 == 0 && i > 0 && commas[Math.floor(i / 3) - 1] != null)
				{
					commas[Math.floor(i / 3) - 1].visible = (s.length > i);
				}
			}
		}

		public function get serial():Number
		{
			return _serial;
		}
	}
}
